#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "sort.h"
#include "words.h"

#include "defs.h"


static const int INDEX_FIRST_FILE = 2;

const char* modifiers = "hVbp";

static struct option long_options[] = {
		{ "help", no_argument, 0, 'h' },
		{ "version", no_argument, 0, 'V' },
		{ "bubble", optional_argument, 0, 'b' },
		{ "heap", optional_argument, 0, 'p' },
		{ 0, 0, 0, 0 }
};

static void
version()
{
	(void)fprintf(stdout,"Organizacion de Computadoras - 6620\n\t\tTP1 - Version 1.0 \n");
}

static void
help()
{
	(void)fprintf(stdout, "usage: tp1 [OPTIONS] [file...]\n");
	(void)fprintf(stdout, "\t\t -h, --help             display this help and exit.\n");
	(void)fprintf(stdout, "\t\t -V, --version          display version information and exit.\n");
	(void)fprintf(stdout, "\t\t -b, --bubble           use the bubblesort algorithm.\n");
	(void)fprintf(stdout, "\t\t -p, --heapsort         use the heapsort algorithm.\n");
}


int main(int argc,char* argv[]){

	int option_index = 0;
	int ch;

	int isBubblesort = 0, isHeapSort = 0;

	// index to first file
	int i = INDEX_FIRST_FILE;
	int nFiles = 0;
	char** filesNames = NULL;

	char** words = NULL;
	int nWords = 0;

	while ((ch = getopt_long(argc, argv, modifiers, long_options, &option_index))!= -1)
		switch((char)ch) {
			case 'V':
				version();
				return NO_ERROR;
				break;
			case 'b':
				isBubblesort = 1; // deberia terminar con una opcion?
				break;
			case 'p':
				isHeapSort = 1; // deberia terminar con una opcion?
				break;
			case 'h':
				help();
				return NO_ERROR;
				break;
			case '?':
				fprintf(stderr,"Error al procesar linea de comandos\n");
				return WRONG_USAGE;
				break;
			default:
				help();
				return WRONG_USAGE;
			}

    //Si el programa se ejecuta sin ningún parametro
    if (argc == 1) {
            fprintf(stderr,"Se esperaba argumentos. Ver ayuda con -h.\n");
            return WRONG_USAGE;
    }

	// Default sort method
	if (!isBubblesort&&!isHeapSort)
	{
		isBubblesort = 1;
		i =  INDEX_FIRST_FILE - 1;
	}

	// Number of files
	nFiles = argc - i;

	// Points to the first file name
	filesNames = &argv[i];

	words = NULL;
	nWords = 0;

	// Si no hay archivos
	if (nFiles <= 0)
	{
		words = ReadWordsFromFile(words, &nWords, stdin);
	}
	else
	{
		words = ReadWordsFromFiles(words, &nWords, filesNames, nFiles);
	}

	//PrintWords(words, nWords);

	if (isBubblesort && nWords)
	{
		bubbleSort(words,nWords);
	}
	else if (isHeapSort && nWords)
	{
		heapSort(words,nWords);
	}
	else if (!nWords)
	{
		exit(1);
	}

	PrintWords(words,nWords);


	if (words)
		FreeWords(words, nWords);

	exit(0);

}
